package org.lgy.sso_client.filter;


import cn.hutool.http.HttpUtil;
import org.lgy.sso_comment.constant.AuthConst;
import org.lgy.sso_comment.storage.SessionStorage;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

/**
 *
 */
@WebFilter(filterName = "LogoutFilter", urlPatterns = "/logout")
public class LogoutFilter implements Filter {

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		String token = (String) session.getAttribute(AuthConst.TOKEN);

		// 主动注销，即子系统提供的注销请求
		session = SessionStorage.INSTANCE.get(token);
		if (session != null) {
			session.invalidate();
			System.out.println(request.getContextPath() + " 主动退出登录");
		}
		// 向认证中心发送注销请求
		HashMap<String, Object> params = new HashMap<>(2);
		params.put(AuthConst.LOGOUT_REQUEST, token);
		HttpUtil.post(AuthConst.LOGOUT_URL, params);

		// 注销后重定向
		response.sendRedirect(request.getContextPath() + "/test");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}